package com.hsl.housaileibot001.ai.bailing;

import cn.tbox.sdk.TboxClient;
import cn.tbox.sdk.core.exception.TboxClientConfigException;
import cn.tbox.sdk.core.exception.TboxHttpResponseException;
import cn.tbox.sdk.model.request.ChatRequest;
import cn.tbox.sdk.model.response.SyncChatResponse;
import cn.tbox.sdk.model.response.TboxResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsl.housaileibot001.model.dto.BailingChatRequestDTO;
import com.hsl.housaileibot001.model.dto.BailingGenerateMockExamDTO;
import com.hsl.housaileibot001.model.vo.MockExamVO;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 白凌非流式聊天服务
 *
 * @author
 */
@Service
public class BailingChatService {

    private final TboxClient tboxClient;
    private final ObjectMapper objectMapper;

    public BailingChatService(TboxClient tboxClient, ObjectMapper objectMapper) {
        this.tboxClient = tboxClient;
        this.objectMapper = objectMapper;
    }

    /**
     * 发起非流式聊天
     *
     * @param requestDTO 请求参数
     * @return 同步聊天响应
     */
    @SuppressWarnings("unchecked")
    public SyncChatResponse chat(BailingChatRequestDTO requestDTO)
            throws TboxClientConfigException, TboxHttpResponseException {
        ChatRequest chatRequest = new ChatRequest(
                requestDTO.getAppId(),
                requestDTO.getQuery(),
                requestDTO.getUserId()
        );
        chatRequest.setStream(false);

        TboxResponse<SyncChatResponse> response = (TboxResponse<SyncChatResponse>) tboxClient.chat(chatRequest);
        return response.getData();
    }

    /**
     * 生成模拟题（结构化输出）
     *
     * @param requestDTO 请求参数
     * @return 模拟题VO
     */
    @SuppressWarnings("unchecked")
    public MockExamVO generateMockExam(BailingGenerateMockExamDTO requestDTO)
            throws TboxClientConfigException, TboxHttpResponseException {
        // 构建提示词，要求返回 JSON 格式的模拟题
        String systemPrompt = """
                你是一名经验丰富的全栈软件架构师，当用户向你提问，你首先要解释这个问题最核心的概念，避免长篇大论，你的回答要简洁精炼，然后给用户出 3 道选择题（包含选项、答案、解析）。
                            
                请严格按照以下 JSON 格式返回结果，不要包含任何其他文本：
                {
                  "mockQuestions": [
                    {
                      "overview": "问题概述",
                      "questionItems": [
                        {
                          "question": "题目内容",
                          "options": [
                            {
                              "optionKey": "A",
                              "optionValue": "选项A内容",
                              "isCorrect": true
                            },
                            {
                              "optionKey": "B",
                              "optionValue": "选项B内容",
                              "isCorrect": false
                            }
                          ],
                          "answer": "A",
                          "explanation": "题目解析"
                        }
                      ]
                    }
                  ]
                }
                """;

        String userQuery = systemPrompt + "\n\n用户问题：" + requestDTO.getUserMessage();

        ChatRequest chatRequest = new ChatRequest(
                requestDTO.getAppId(),
                userQuery,
                requestDTO.getUserId()
        );
        chatRequest.setStream(false);

        TboxResponse<SyncChatResponse> response = (TboxResponse<SyncChatResponse>) tboxClient.chat(chatRequest);
        String chunkText = getChunkText(response);

        // 解析 chunk 中的 JSON 并转换为 MockExamVO
        try {
            return objectMapper.readValue(chunkText, MockExamVO.class);
        } catch (Exception e) {
            throw new TboxHttpResponseException("解析 JSON 响应失败：" + e.getMessage(), e);
        }
    }

    @NotNull
    private static String getChunkText(TboxResponse<SyncChatResponse> response) throws TboxHttpResponseException {
        SyncChatResponse syncResponse = response.getData();

        // 从 SyncChatResponse 的 result 列表中获取第一个 Answer 的 chunk 字段
        if (syncResponse == null || syncResponse.getResult() == null || syncResponse.getResult().isEmpty()) {
            throw new TboxHttpResponseException("响应中未找到 result 数据");
        }

        SyncChatResponse.Answer firstAnswer = syncResponse.getResult().getFirst();
        String chunkText = firstAnswer.getChunk();

        if (chunkText == null || chunkText.trim().isEmpty()) {
            throw new TboxHttpResponseException("响应中的 chunk 字段为空");
        }
        return chunkText;
    }

    public void streamChatWithFiles(ChatRequest chatRequest) throws TboxHttpResponseException, TboxClientConfigException {
        @SuppressWarnings("unchecked")
        Iterable<Map<String, Object>> response = (Iterable<Map<String, Object>>) tboxClient.chat(chatRequest);
        for (Map<String, Object> chunk : response) {
            System.out.println(chunk); // 输出流式响应
        }
    }

    /**
     * 上传文件到白凌服务器
     * @param filePath 文件路径
     * @return 文件上传响应，包含文件 ID
     */
    public TboxResponse<String> uploadFile(String filePath) throws TboxClientConfigException, TboxHttpResponseException {
        return tboxClient.uploadFile(filePath);
    }
}


